package org.chimi.rr4s.setup;

import java.io.File;

import org.simplericity.datadirlocator.DataDirectoryLocator;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.ConfigurableWebApplicationContext;

/**
 * @author Choi, Beom Kyun
 */
public class ContextReloader implements ApplicationContextAware,
		ApplicationListener<ContextRefreshedEvent> {

	private DataDirectoryLocator dataDirectoryLocator;
	private ApplicationContext applicationContext;

	public void reloadContext() {
		if (applicationContext instanceof ConfigurableWebApplicationContext) {
			ConfigurableWebApplicationContext configurableCtx = (ConfigurableWebApplicationContext) applicationContext;
			String[] configLocations = { "classpath:/spring-application.xml",
					"classpath:/spring-mvc.xml", "classpath:/spring-rest.xml" };
			configurableCtx.setConfigLocations(configLocations);
			configurableCtx.refresh();
		}
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		File homeDirectory = locateHomeDirectory();
		if (existConfigFileIn(homeDirectory)) {
			reloadContext();
		}
	}

	private File locateHomeDirectory() {
		return dataDirectoryLocator.locateDataDirectory();
	}

	private boolean existConfigFileIn(File homeDirectory) {
		return new File(homeDirectory, "conf.properties").exists();
	}

	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		this.applicationContext = context;
	}

	public void setDataDirectoryLocator(
			DataDirectoryLocator dataDirectoryLocator) {
		this.dataDirectoryLocator = dataDirectoryLocator;
	}

}
